﻿@model planerka.DataAccess.Models.task

@using planerka.Common.Enums; 
@using planerka.Common;   
@using planerka.DataAccess.DataService;   
@using planerka.DataAccess.Models; 

@{
    user currentUser = new UserService().getCurrentUser();

    Html.EnableClientValidation();

    bool rightsEdit = Model.rightsEditDelete;
    bool rightsView = Model.rightsView;
    //object Readonly = new { @readonly = "readonly" };
    //object htmlDisabledAttrib = new object();
    string readonlyClass = "";
    string disabledString = ""; 
    if (!rightsEdit)
    {
        //Readonly = new { @readonly = "readonly" };
        //htmlDisabledAttrib = new { @disabled = "disabled" };
        readonlyClass = "readonly";
        disabledString = "disabled=disabled";
    }
}

<script src="@Url.Content("~/Scripts/MicrosoftAjax.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/MicrosoftMvcAjax.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/MicrosoftMvcValidation.js")" type="text/javascript"></script>

<script src="@Url.Content("~/Scripts/ui/jquery.ui.core.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/ui/jquery.ui.widget.js")" type="text/javascript"></script>

<link rel="stylesheet" href="@Url.Content("~/Content/jquery.ui.theme-overcast.css")" type="text/css" />

<link rel="stylesheet" href="@Url.Content("~/Content/jquery.ui.datepicker.css")"  type="text/css" />
<link rel="stylesheet" href="@Url.Content("~/Content/jquery.ui.core.css")"  type="text/css" />
<script type="text/javascript" src="@Url.Content("~/Scripts/ui/jquery.ui.datepicker.js")"></script>
<script type="text/javascript" src="@Url.Content("~/Scripts/ui/jquery.ui.datepicker-ru.js")"></script>

<script type="text/javascript">

    function loadScripts() {
        //xhr, status
        setTimeout('closeResultMessage()', 3000);

        $.datepicker.setDefaults($.datepicker.regional[""]);
        $(".dateField").datepicker($.datepicker.regional["ru"]);

        // управляем видимостью
        showHideIfPeriodical($("#taskStatus")[0].value);

        $("#taskStatus").change(function () {

            var taskStatusID = $(this)[0].value; // get value
            $(this).parent().removeClass('taskStatus1 taskStatus2 taskStatus3 taskStatus4 taskStatus5');
            $(this).parent().addClass('taskStatus' + taskStatusID);

            showHideIfPeriodical(taskStatusID);

            // сбросить аттрибут "disabled" для дат
            $(".dateField").removeAttr("disabled");
        });

        // add cascading DDL functionality
        $("#taskCustomer_ID").change(function () {

            taskCustomer_ID = $(this)[0].value;
            $("#ajax-loading").show();
            $.ajax({
                url: '@Url.Content("~/projectsForCustomer")',
                type: "GET",
                data: { 'taskCustomer_ID': $(this)[0].value },
                dataType: "json",
                success: function (result) {
                    $("#taskProject_ID").empty();
                    $.each(
                     result, function (index, optionData)
                     { $("#taskProject_ID").append("<option value='" + optionData.Value + "'>" + optionData.Text + "</option>") });

                },
                complete: function (result) {
                    $("#ajax-loading").hide();
                 }
            });
        });
    }

//    // стереть ResultMessage
//    function closeResultMessage() {
//        $(".resultMessage").html("");
//     }

    function showHideIfPeriodical(taskStatusID) {
        if (taskStatusID == 5) {
            $('#startFinishTable').hide();
            $('#periodicalTable').show();
            
        } else {
            $('#startFinishTable').show();
            $('#periodicalTable').hide();
        }
    }

    $(function () {
        loadScripts();
    });
</script>
 

<div class="editItem @readonlyClass" id="taskDiv">  
       
    @Html.ValidationSummary(true)

    
    @if (rightsEdit)
    {
        <h2 style="float: left;">@Model.caption</h2>
        <input type="submit" value="Сохранить" class="save" name="confirmButton" />
        <img src="@Url.Content("~/Content/images/ajax-loader.gif")" alt="load" id="ajax-loading" style="display: none;" />
        }
    else
    { 
        <h2 style="float: left;">@Model.caption</h2>
    }
     <div class="clear"></div>
     <fieldset class="fieldsetControl" style="width: 840px;">
        <span class="resultMessage">@Html.Raw(ViewData["resultMessage"] != null ? ("<span>" + ViewData["resultMessage"] + "</span>") : "")</span> 
    </fieldset>

    <fieldset class="fieldsetEdit" style="width: 800px;">
       @* <legend>Задача</legend>*@

        @*@Html.HiddenFor(model => model.ID)*@
        @*@Html.Hidden("ID", Model.ID)*@
        <input type="hidden" value="@Html.AttributeEncode(Model.ID)" id="ID" name="ID" />

        <div class="editor-label">
            Наименование задачи
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(model => model.taskName, rightsEdit ? (object)new { @class = "taskTextBox" } : (object)new { @class = "taskTextBox", @readonly = "readonly" })
            @Html.ValidationMessageFor(model => model.taskName)
        </div>

        <div class="editor-label">
            Описание задачи
        </div>
        <div class="editor-field">
            @Html.TextAreaFor(model => model.taskDescription,
            rightsEdit ? (object)new { style = "height: 140px;", @class = "taskTextBox"} : (object)new { style = "height: 140px;", @class = "taskTextBox", @readonly = "readonly" } )

            @Html.ValidationMessageFor(model => model.taskDescription)
        </div>

        <div class="oneThird">
            @{
                List<SelectListItem> stList = new List<SelectListItem>();
                stList = planerka.Common.tools.getEnumSelectList<taskStatuses>().ToList();

                string taskStatus = "";
                if (Enum.IsDefined(typeof(taskStatuses), Model.taskStatus))
                {
                    taskStatus = ((taskStatuses)Model.taskStatus).ToString();
                }

                string taskStatusClass = "taskStatus" + Model.taskStatus;
              } 
            <div class="editor-label divInputs">
                Статус задачи: 
             </div> 
            <div class="editor-field divInputs @taskStatusClass">
                @if (rightsEdit)
                { 
                    @Html.DropDownList("taskStatus", new SelectList(stList, "Value", "Text", Model.taskStatus), new { @class = "filterInputs" })}
                else 
                {
                    @Html.DropDownList("taskStatus", new SelectList(stList, "Value", "Text", Model.taskStatus), new { @style = "display:none;" })
                    @Html.TextBox("taskStatusView", ((taskStatuses)Model.taskStatus).ToString(), new { @class = "filterInputs" })
                }                                                                                                                                                                  
            </div>

       </div>

       <div class="oneThird">
       <div class="editor-label">
            Приоритет
        </div>
        <div class="editor-field">
        @{
            stList = new List<SelectListItem>();
            stList = planerka.Common.tools.getEnumSelectList<priorities>().ToList();
          } 
          @if (rightsEdit)
          {@Html.DropDownList("priority", new SelectList(stList, "Value", "Text", Model.priority), new { @class = "filterInputs" })}
          else
          { 
            @Html.TextBox("priorityView", ((priorities)Model.priority).ToString(), new { @class = "filterInputs" })
          }
        </div>
         </div>
        <div class="clear"></div>

        <fieldset style="border: 1pt solid #ddd; padding: 10px; margin: 20px 0px; width: 760px;">
       
            <table id="startFinishTable">
                <tr>
                    <td class="editor-label">План старт&nbsp;</td>
                    <td style="width: 160px;">
                       
                        <input id="planStartString" name="planStartString" value="@tools.getStringFromNullableDateTime(Model.planStart)" type="text" class="dateField" @disabledString />
                        
                        </td>
                    <td class="editor-label">План финиш&nbsp;</td>
                    <td style="width: 160px;">
                     
                        <input id="planFinishString" name="planFinishString" value="@tools.getStringFromNullableDateTime(Model.planFinish)" type="text" class="dateField" @disabledString />
                    </td>
                    <td class="editor-label">
                    @if (Model.planStart != null && Model.planFinish != null)
                    {
                        @:всего дней: @(((DateTime)Model.planFinish).Subtract((DateTime)Model.planStart).Days)
                    }
                    </td>
                </tr>
                <tr>
                    <td class="editor-label">Факт старт&nbsp;</td>
                    <td>
                        @{ string factStartDS = disabledString;

                           if (Model.taskStatus == taskStatuses.Новая.GetHashCode() || Model.taskStatus == taskStatuses.Периодическая.GetHashCode())
                           {
                               factStartDS = "disabled=disabled";
                           }

                        <input id="factStartString" name="factStartString" value="@tools.getStringFromNullableDateTime(Model.factStart)" type="text" class="dateField" @factStartDS />
                        }
                    </td>
                    <td class="editor-label">Факт финиш&nbsp;</td>
                    <td>
                       @{ string factFinishDS = disabledString;

                          if (Model.taskStatus != taskStatuses.Выполнена.GetHashCode())
                          {
                              factFinishDS = "disabled=disabled";
                          }

                        <input id="factFinishString" name="factFinishString" value="@tools.getStringFromNullableDateTime(Model.factFinish)" type="text" class="dateField" @factFinishDS />
                        }
                        
                    </td>
                    <td class="editor-label">
                        @if (Model.factStart != null && Model.factFinish != null)
                        {
                        @:всего дней: @(((DateTime)Model.factFinish).Subtract((DateTime)Model.factStart).Days)
                    }
                    </td>
                </tr>
            </table>
       
            <div id="periodicalTable">
                <div class="oneThird" style="width: 240px !important;">
                    <label>
                        @Html.CheckBoxFor(model => model.periodicalIsOn, rightsEdit ? (object)new { } : (object)new { disabled="disabled"}) <span class="editor-label" style=" font-weight: bold;">Включена</span>
                    </label>
                </div>
                <div class="oneThird" style="width: 240px !important;">
                    <label>

                    @{ string _checkedEveryMonthDay = ((Model.periodicalEveryMonthDay == null && Model.periodicalEveryWeekDay == null) || Model.periodicalEveryMonthDay != null) ? @"checked=""checked""" : "";
                       string _checkedEveryWeekDay = (Model.periodicalEveryWeekDay != null) ? @"checked=""checked""" : ""; 
                       }
                        @{
                                
                            <input id="Checkbox_periodicalEveryMonthDay" value="monthDay" @disabledString type="radio" name="periodicalType" @_checkedEveryMonthDay />
                        }
                        <span class="editor-label">запуск каждый день месяца</span>
                    </label>
                    <br />
                    @{ List<SelectListItem> days = new List<SelectListItem> { };
                       for (int i = 1; i <= 31; i++)
                       {
                           days.Add(new SelectListItem { Text = i.ToString(), Value = i.ToString() });
                       } 
                       }
                       @if (rightsEdit)
                       {@Html.DropDownList("periodicalEveryMonthDay", new SelectList(days, "Value", "Text", Model.periodicalEveryMonthDay), 
                       rightsEdit ? (object)new { @class = "filterInputs"}: (object)new { @class = "filterInputs", disabled= "disabled" })}
                       else
                       {
                           if (Model.periodicalEveryMonthDay != null)
                           {
                               @Html.TextBox("periodEveryMonthDayView", Model.periodicalEveryMonthDay.ToString(), new { @class = "filterInputs" })
                           }
                       }

                </div>

                <div class="oneThird">
                    <label>
                        <input id="Checkbox_periodicalEveryWeekDay" @disabledString type="radio" value="weekDay" name="periodicalType" @_checkedEveryWeekDay />
                        
                        <span class="editor-label">
                        запуск каждый день недели</span>
                    </label>
                    <br />
                    @{ List<SelectListItem> weekdays = new List<SelectListItem> { };


                       for (int i = 1; i < 7; i++)
                       {
                           weekdays.Add(new SelectListItem
                           {
                               Value = ((weekDays)i).GetHashCode().ToString(),
                               Text = ((weekDays)i).ToString()
                           });

                       }
                       weekdays.Add(new SelectListItem
                       {
                           Text = weekDays.Воскресенье.ToString(),
                           Value = weekDays.Воскресенье.GetHashCode().ToString()
                       });
                       
                       }
                       @if (rightsEdit)
                       { @Html.DropDownList("periodicalEveryWeekDay",
                                         new SelectList(weekdays, "Value", "Text", Model.periodicalEveryWeekDay), 
                                         rightsEdit ? (object)new { @class = "filterInputs"}: (object)new { @class = "filterInputs", disabled= "disabled" }) }
                       else 
                       { 
                           if (Model.periodicalEveryWeekDay != null)
                           {
                                @Html.TextBox("periodEveryWeekDayView", weekdays.Where(p => p.Value == Model.periodicalEveryWeekDay.ToString()).First().Text, new { @class = "filterInputs" })
                           }
                       }
                </div>
            </div>
        </fieldset>

         <div class="oneThird">
         <div class="editor-label">
            <span title="Показывается список только тех пользователей (Заказчиков) у которых есть проекты">Заказчик</span>
         </div>
         <div class="editor-field">
            @{
                // здесь надо получить список пользователей, 
                // которые указаны в моих (администратора) проектах как заказчики
                UserService userService = new UserService();
                List<SelectListItem> userList = userService.getMyCustomers(currentUser.ID).Select(p => new SelectListItem
                {
                    Text = p.surName + " " + p.firstName + " " + p.middleName,
                    Value = p.ID.ToString()
                }).ToList();

                userList.Insert(0, new SelectListItem { Text = "", Value = "0" });

                string selectedCustomer_ID = "0";
                project _project = new ProjectService().getProjectsList(currentUser.ID).Where(p => p.ID == Model.project_ID).FirstOrDefault();
                selectedCustomer_ID = _project.customer_ID != null ? _project.customer_ID.ToString() : "0";
                
                string selectedCustomerString = "";
                if (selectedCustomer_ID != "0")
                {
                    user selectedCustomer = userService.getUserByID(Int64.Parse(selectedCustomer_ID));
                    if (selectedCustomer != null)
                    { selectedCustomerString = selectedCustomer.nameView; }
                }
                
            }
            @if (rightsEdit)
            {
                @Html.DropDownList("taskCustomer_ID", new SelectList(userList, "Value", "Text", selectedCustomer_ID), new { @class = "filterInputsMiddle" })
            }
            else
            {
                @Html.TextBox("taskCustomerView", selectedCustomerString, new { @class = "filterInputsMiddle" })
            }
            
        </div>

         <!-- проект -->
         <div class="editor-label">
            Проект
         </div>
         <div class="editor-field">
            @{
                // получить список проектов, в которых я - администратор
                ProjectService projectService = new ProjectService();
                string selectedProjectString = "";
                IEnumerable<project> projects = projectService.getProjectsList(currentUser.ID)
                    .Where(p => p.owner_ID == currentUser.ID);

                // Если заказчик выбран - отфильтровать по заказчику
                if (Model.project != null)
                {
                    selectedProjectString = Model.project.projectName;
                    if (Model.project.customer_ID != null)
                    { projects = projects.Where(p => p.customer_ID == Model.project.customer_ID); }
                }
                List<SelectListItem> projectList = projects.Select(p => new SelectListItem
                {
                    Text = p.projectName,
                    Value = p.ID.ToString()
                }).ToList();


            }
            @if (rightsEdit)
            { @Html.DropDownList("taskProject_ID", new SelectList(projectList, "Value", "Text", Model.project_ID), new { @class = "filterInputsMiddle" }) }
            else
            {
                @Html.TextBox("taskProjectView", selectedProjectString, new { @class = "filterInputsMiddle", disabled="disabled" })
            }
         </div>

         <!-- Исполнитель -->
         <div class="editor-label">
            <span title="Показывается список пользователей, для которого задана роль 'Исполнитель'">Исполнитель</span>
         </div>
         <div class="editor-field">
            @{
                // здесь надо получить список пользователей, 
                // которые указаны в моих (администратора) проектах как исполнители или реальные пользователи
                userList = userService.getUserList(currentUser.UserId)
                    .Where(p => p.isPerformer || (p.isEmailApproved && p.ID != currentUser.ID)).Select(p => new SelectListItem
                {
                    Text = p.nameView,
                    Value = p.ID.ToString()
                }).ToList();

                userList.Insert(0, new SelectListItem { Text = "", Value = "0" });

                string selectedPerformerString = "";
                if (Model.performer_ID != null)
                {
                    user selectedPerformer = userService.getUserByID((long)Model.performer_ID);
                    if (selectedPerformer != null)
                    { selectedPerformerString = selectedPerformer.nameView; }
                }
                
            }
            @if (rightsEdit)
            { @Html.DropDownList("taskPerformer_ID", new SelectList(userList, "Value", "Text", Model.performer_ID), new { @class = "filterInputsMiddle" })}
            else 
            {
              @Html.TextBox("taskPerformerView", selectedPerformerString, new { @class = "filterInputsMiddle", disabled="disabled" })  
            }
            
        </div>
         </div>
             
        
         

         @if (rightsEdit && Model.ID != 0)
         {
             <div id="paymentDiv">
             <span class="editor-label">Сумма: </span><span class="editor-field">
                 @Html.TextBoxFor(model => model.sumPlanned, new { style = "width: 80px;" })
                 @Html.ValidationMessageFor(model => model.sumPlanned, "Введите целое число")
             </span>
             
             <div class="editor-label">
                 Платежи по задаче <i>(+ приход, - расход)</i>
             </div>
         <div style="margin-bottom: 10px;">
         


        </div>
             <div id="paymentTableDiv">
                @Html.Hidden("task_ID", Model.ID)
                @{ Html.RenderPartial("_taskPaymentsTable", Model); } 
              </div>
            
            
            @if (Model.ID == 0)
            { 
                <div style="color:Red;">Для регистрации платежей сначала сохраните задачу!</div>
            }
         </div>
        }
         <div class="clear"></div>

    </fieldset>
    </div>
    @if (rightsView && !Model.isNew)
    { 
    <div class="messagesDiv" style="">

    <h4>Сообщения к задаче</h4>
    @{
        MessagesService messagesService = new MessagesService();
        List<message> messages = messagesService.getMessagesForTask(Model.ID);
        List<user> taskUsers = messagesService.getUsersForTask(Model.ID);
        user userToRemove = taskUsers.Where(p => p.ID == currentUser.ID).FirstOrDefault();
        if (userToRemove != null) { taskUsers.Remove(userToRemove); }

        taskUsers.Insert(0, new user { ID = 0, nameView = " " });
        <ul>
        @foreach (var messageItem in messages)
        {
            <li>
                
                <span class="b_first">Отправитель:<span> @messageItem.fromUserName </span></span>
                <span class="b_second">Получатель:<span> @messageItem.toUserName </span></span>
                <div>
                    <i>@messageItem.timestamp</i> <br/>
                     @Html.Raw(messageItem.text.Replace("\n", "<br />"))  
                </div>
            </li>      
        }
        </ul>
      }

    @Html.TextAreaFor(model => model.addMessage, new { style = "width: 600px; height: 100px; float: right; margin-bottom: 10px;" })
    <br />
    
    
    <input id="iSubmitButton_addMessage" type="submit" value="Добавить сообщение"  name="confirmButton" style="float: right;" />
    @if (taskUsers.Count > 1)
    {
        <text>
        &nbsp; &nbsp;
    @Html.DropDownList("sendMessageTo", new SelectList(taskUsers, "ID", "nameView"), new { style = "float: right; margin-right: 10px;" })
    &nbsp;<a style="float: right; margin-top: -6px;" title="Выберите получателя - ему будет отправлена копия сообщения на его адрес e-mail. Вы можете оставить поле пустым." class="tooltip">
                    <img alt="?" src="@Url.Content("~/Content/images/question.gif")" />
     </a><span style="float: right;">Кому</span>
     </text>
    }
    <div class="clear"></div>
    </div>
    }





